﻿var add, //添加图片函数
    autoNum = 1, //用来产生不同的file
    picNum = 0, //图片个数
    submitbtn = $(".AP-bco"), //提交按钮
    file = $(".AP-a-file"), //file容器
    fileHiddden = $(".hf_files"), //file值的隐藏域
    nulldata = $(".nulldata"), //无数据时提示容器
    filebox = $(".AP-a-l-words");

/*fileupload对象 :
  ini:iframe初始化
  loadFile:初始化附件容器。
  addFile:添加附件
  checkFile：检验file类型
  replaceToOriginal：替换file的name值
  iniListFile:初始化file
  saveFile：保存file
  deleteFile:删除file
  getArgs:获取url的参数*/
var fileupload = {
    ini: function () {
        var $frame = $("<iframe name='frame234' id='frame234' class='dn' />");
        var $form = $("<form id='idForm' enctype='multipart/form-data' method='POST' action='/FileUpload/Swfupload' target='frame234' class='dn' />");
        $('body').prepend($form).prepend($frame);
    } (),
    loadFile: function () {
        var url = location.href;
        if (fileHiddden.length > 0 && fileHiddden.val() != "") {
            var arrfileName = eval("(" + fileHiddden.val() + ")");
            this.addPic(arrfileName);
        } else {
            if (url.indexOf("type") > 0) { //查看附件时无数据提示
                $(".AP-a-pic").removeClass("dn").addClass("AP-a-pic-noData").html("暂无附件！");
            }
        }
    } (),
    addFile: function (arrFileName) {
        nulldata.addClass("dn");
        for (var i = 0; i < arrFileName.length; i++) {
            var $spanD = $("<a class='AP-a-p-i'  href='" + arrFileName[i].Url + "'>" + arrFileName[i].Name + "</a>"), $deleteicon = '';
            if (this.getArgs().type != "view") {
                $deleteicon = $('<span class="AP-a-p-delete"  data_name="' + arrFileName[i].Url + '"></span>');
            }
            var $a = $("<a  class='AP-a-p-item'></a>");
            filebox.append($a.append($spanD).append($deleteicon));
            picNum++;
        }
    },
    checkFile: function ($obj) {
        var bCheck = true;
        var fileName = $obj.get(0).value;
        if (!fileName) { //检测空值
            bCheck = false;
        } else {
            var reg = /\.(xls|xlsx)$/gi; //检测后缀
            if (!reg.test(fileName)) {
                bCheck = false;
                alert("请上传xls|xlsx格式的文件");
                this.replaceToOriginal($obj);
            } 
        }
        return bCheck;
    },
    replaceToOriginal: function ($obj) {
        $obj.remove();
        var $aPafiles = $(".AP-a-files"); //file容器
        $aPafiles.append("<input name='file" + (++autoNum) + "' class='AP-a-file AP-a-f-active' type='file' />");
    },
    iniListFile: function () {
        $(".AP-a-l-words").removeClass("dn");
        $(".AP-a-file").remove();
        $(".AP-a-l-item").remove();
        $(".AP-a-files").append("<input name='file" + (++autoNum) + "' class='AP-a-file AP-a-f-active' type='file' onChange='fileChange(this);'/>");
    },
    saveFile: function () {
        var $picName = $(".AP-a-p-i"), sName;
        if ($picName.length > 0) {
            sName = "[";
            $picName.each(function () {
                if (sName == "") {
                    sName += "{ 'Name': '" + $(this).html() + "', 'Url': '" + $(this).attr("href") + "' }";
                } else {
                    sName += "{ 'Name': '" + $(this).html() + "', 'Url': '" + $(this).attr("href") + "' },";
                }
            });
            sName += "]";
            if (sName.indexOf(",")) {
                sName = sName.substring(0, sName.length - 2) + ']';
            }
        }
        fileHiddden.val(sName);
    },
    deleteFile: function (delIndex) {
        if (confirm("是否确定删除此附件？")) {
            var fileName = delIndex.attr("data_name"), thishref, url = location.href;
            if (url.indexOf("?") > 0) { //判断是不是修改页面
                var loadvalue = fileHiddden.val(),
                    arrfileName = '';
                if (fileHiddden.length > 0 && loadvalue != "") {
                    arrfileName = eval("(" + loadvalue + ")");
                }
                delIndex.parent().remove();
                picNum--;
                thishref = delIndex.prev().attr('href');
                for (var j = 0; j < arrfileName.length; j++) {
                    if (arrfileName[j].Url == thishref) {
                        arrfileName.splice(j, 1);
                    }
                }
                if (arrfileName.length == 0) {
                    fileHiddden.val('');
                    nulldata.show();
                }
                else {
                    fileHiddden.val(JSON.stringify(arrfileName));
                }
            } else {
                $.post("/FileUpload/DelFile", { fileName: fileName },
                function (data) {
                    if (data == "ok") {
                        alert("删除成功!");
                        delIndex.parent().remove();
                        picNum--;
                        if (picNum == 0) {
                            nulldata.removeClass("dn");
                        }
                    } else {
                        alert(data);
                    }
                });
            }
        }
    },
    getArgs: function getArgs() {
        var args = new Object(),
            query = location.search.substring(1),
            pairs = query.split("&");
        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue;
            var argname = pairs[i].substring(0, pos),
                value = pairs[i].substring(pos + 1);
            value = decodeURIComponent(value);
            args[argname] = value;
        }
        return args;
    }
};

       //附件的上传
    fileChange = function (item) {
        var $files = $(".AP-a-file"),
               $self = $(item),
               iframeB = $("#idForm");
        iframeB.append($files);
        if (fileupload.checkFile($self)) {
            iframeB.submit();
            $(".shade").show();
        }
        fileupload.iniListFile();
    };
   
    //添加图片函数定义返回时后台直接调用的js方法
    add = function (msg, data) {
        if (data != "1") {
            fileupload.addFile(data);
            $.ajax({
                url: window.jkconfig.webapiurlv + "sys/datamanager/import",
                data:{file:data[0].Url},
                async: false,
                type: "POST",
                success: function (returndata) {
                    $(".AP-a-p-item").remove();
                    $.ajax({
                        url: window.jkconfig.webapiurlv + "sys/datamanager/import",
                        //url: encodeURI("/FileUpload/DelFile1?filepath=" + data[0].Url + "&currentdate=" + new Date().getMilliseconds().toString()),
                        async: false,
                        type: "POST",
                        success: function () {
                            $(".shade").hide();
                            if (returndata != "True") {
                                alert(returndata + "请重新上传");
                            } else {
                                alert("上传成功");
                                // window.location.reload();
                                window.location.href = window.location.href;
                            }

                        }
                    });
                    $(".shade").hide();
                }
            });
        } else {
            alert(msg);
        }
    };

    //确定按钮file保存到数据库中
    submitbtn.bind("click", function () {
        fileupload.saveFile();
    });

   //删除图片
    $(".AP-a-p-delete").on("click", function () {
        var self = $(this);
        fileupload.deleteFile(self);
    });